import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:myflutterproject/basematerialwidgetsdemo.dart';
import 'package:myflutterproject/views/myimagebutton.dart';
import 'package:myflutterproject/views/sceniccard.dart';
import 'package:myflutterproject/views/sceniccard2.dart';
import 'package:myflutterproject/views/slidershowwidget.dart';
import 'package:myflutterproject/widget/commonWidget.dart';

class FollowMeiTuanDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => FollowMeiTuanState();
}

class FollowMeiTuanState extends State<FollowMeiTuanDemo> {
  late ScrollController _controller;
  late bool isRefreshing;
  late Widget _selectedItem;
  late GlobalKey<AnimatedListState> _listKey;
  late List<Widget> _list;

  //主界面AppBar
  AppBar _buildFollowAppBar() {
    return AppBar(
      //取消自动显示返回按钮
      automaticallyImplyLeading: false,
      //关闭阴影高度
      elevation: 0.0,
      backgroundColor: Color(0xFFF5F5F5),
      //适配刘海，自动避开刘海，IOS底部导航的非显示区域
      flexibleSpace: SafeArea(
        child: Row(
          //垂直居中
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            //水波纹效果
            InkWell(
              //水波纹特效边角弧度
              borderRadius: BorderRadius.circular(45),
              //点击事件回调
              onTap: () => print("水波纹-头像"),
              child: Padding(
                //增加水平方向外边距
                padding: EdgeInsets.symmetric(horizontal: 10.0),
                child: ClipOval(
                  //圆形图片
                  child: Image.asset(
                    'images/protrait.png',
                    width: 35.0,
                    height: 35.0,
                  ),
                ),
              ),
            ),
            InkWell(
              onTap: () => print("地址选择"),
              //Container 里面只能放一个子child
              child: Container(
                //Column 里面可以放多个子Widget  定义的是一组Widget在Y轴，也就是纵轴上的排列方式
                child: Column(
                  //crossAxisAlignment 水平方向上  居左   mainAxisAlignment  垂直方向上
                  crossAxisAlignment: CrossAxisAlignment.start,
                  //设置Column占据的空间min自适应   max为最大
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    //水平对齐方式 横轴对齐方式
                    Row(
                      //水平居中
                      mainAxisAlignment: MainAxisAlignment.center,
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Text(
                          "郑州",
                          style: TextStyle(color: Colors.black, fontSize: 15),
                        ),
                        Icon(
                          Icons.keyboard_arrow_down,
                          size: 15,
                        )
                      ],
                    ),
                    Text(
                      "晴 20°",
                      style: TextStyle(fontSize: 10),
                    )
                  ],
                ),
                padding: EdgeInsets.all(8),
              ),
            ),
            //标题栏搜索部分   Expanded占满剩余空间
            Expanded(
                //GestureDetector 手势处理
                child: GestureDetector(
              onTap: () => {print('搜索界面')},
              child: Container(
                height: 45,
                child: Card(
                  elevation: 0.0,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  color: Colors.grey[300],
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Icon(
                        Icons.search,
                        color: Colors.black87,
                        size: 18,
                      ),
                      Text('自助烤肉')
                    ],
                  ),
                ),
              ),
            )),
            //标题右侧菜单
            Padding(
              padding: EdgeInsets.all(8.0),
              //按钮展示样式
              child: PopupMenuButton(
                child: Icon(
                  Icons.add,
                  size: 30,
                  color: Colors.black,
                ),
                //弹窗内容
                itemBuilder: (context) => <PopupMenuEntry>[
                  PopupMenuItem(
                      //扫一扫菜单
                      child: Container(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(Icons.image),
                        SizedBox(
                          width: 20,
                        ),
                        Text("扫一扫"),
                      ],
                    ),
                  )),
                  //付款码菜单
                  PopupMenuItem(
                      child: Container(
                    //水平布局
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(Icons.scanner),
                        SizedBox(
                          width: 20,
                        ),
                        Text("付款码"),
                      ],
                    ),
                  ))
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState(); //调用父类的initState方法
    _controller = ScrollController();
    _controller.addListener(() {
      //给ScrollController添加监听器
      if (_controller.position.pixels == _controller.position.maxScrollExtent &&
          !this.isRefreshing) {
        //当滚动到底部且不在加载中时
        isRefreshing = true; //设置当前状态为正在加载中
        Widget item = Container(
          //一个IOS风格的加载中的指示器
          height: 50,
          child: Center(child: CupertinoActivityIndicator()),
        );
        _selectedItem = item; //设置当前选中的控件为该指示器，方便加载完后删除指示器
        _insertItem(_list.length, item); //添加该指示器到底部

        /* Future.delayed(Duration(seconds: 2), () {
          //两秒后执行传入的方法
          _removeItem(_list.length - 1); //删除指示器并添加三个推荐卡片
          _insertItem(_list.length, _buildCard1());
          _insertItem(_list.length, _buildCard2());
          _insertItem(_list.length, _buildCard3());
          isRefreshing = false; //设置当前状态为不在加载中
        });*/
      }
    });
  }

  void _insertItem(int index, Widget item) {
    _list.insert(index, item); //从控件列表和key中添加一个控件
    _listKey.currentState!.insertItem(index + 6);
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;

    //顶部三行标题栏及轮播图等不会被删除的控件，因含有用于分隔的SizedBox控件，所以总长度为6
    final bodys = _initBody(screenWidth);
    return Scaffold(
        appBar: _buildFollowAppBar(),
        backgroundColor: Color(0xFFF5F5F5),
        body: ListView(
          //第一行图文
          children: bodys,
        ));
  }

  //首页头部tab
  List<Widget> _initBody(double screenWidth) {
    const title1 = <String>["美食", "电影/演出", "酒店住宿", "休闲娱乐", "外卖"];
    const url1 = <String>[
      "images/title/18.png",
      "images/title/17.png",
      "images/title/16.png",
      "images/title/19.png",
      "images/title/20.png",
    ];
    const title2 = <String>["亲子", "健身/游泳", "周边游/旅游", "丽人/美发", "超市/生鲜"];
    const url2 = <String>[
      "images/title/6.png",
      "images/title/7.png",
      "images/title/8.png",
      "images/title/9.png",
      "images/title/10.png",
    ];
    const title3 = <String>["医疗/牙科", "生活服务", "景点/门票", "签到领现金", "更多"];
    const url3 = <String>[
      "images/title/11.png",
      "images/title/12.png",
      "images/title/13.png",
      "images/title/14.png",
      "images/title/15.png",
    ];
    const tip1 = <String>["", "", "嗨抢", "网咖", ""];

    const imageUrls = <String>[
      "https://p1.meituan.net/hotel/828cc5794f92e40c5de5182cb1b30993316981.jpg@220w_125h_1e_1c",
      "http://p1.meituan.net/hoteltdc/998c2b9face5e48942e10b90bf42803a154752.jpg",
      "http://p0.meituan.net/hotel/aaa8a7aed2ce2fe43aea50d6616293b2119956.jpg"
    ];

    const imageUrls2 = <String>[
      "http://p0.meituan.net/travel/83544ca4b38bbe0f7644982c3528defd117921.jpg@660w_500h_1e_1c",
      "http://p1.meituan.net/poi/e732ed2314a1a2619e6c3254fd2f1fd0112611.jpg",
      "http://p0.meituan.net/poi/e7d94c4d609e5dd4d71bcea6a5eb0c5e220371.jpg"
    ];

    const tags = <String>['销量火爆', '双人餐'];
    const tags1 = <String>['网红打卡地', '帝王宫殿', '5A景区'];
    const tags2 = <String>['城市地标', '陪爸妈'];
    return <Widget>[
      //第一行图文
      Container(
        padding: EdgeInsets.symmetric(horizontal: 10),
        // color: Color(0xFFEDEDED),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: _buildTitle(title1, url1, tip1, (screenWidth - 100) / 5),
        ),
      ),
      SizedBox(
        height: 10,
      ),
      //第二行图文
      Container(
        padding: EdgeInsets.symmetric(horizontal: 10),
        // color: Color(0xFFEDEDED),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children:
              _buildTitleWithOutRed(title2, url2, (screenWidth - 220) / 5),
        ),
      ),
      // SizedBox(height: 10,),
      //第三行图文
      Container(
        padding: EdgeInsets.symmetric(horizontal: 10),
        color: Color(0xFFF5F5F5),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children:
              _buildTitleWithOutRed(title3, url3, (screenWidth - 220) / 5),
        ),
      ),
      //轮播图
      Container(
        padding: EdgeInsets.only(left: 10, right: 10, top: 15, bottom: 0.0),
        child: SliderShowWidget(
          height: 80,
        ),
      ),
      //条目
      ScenicCard('5', '故宫博物馆', imageUrls, '4.0', ' | 后海/什刹海', tags1,
          _showDeleteDialog),
      SceniCard2(
          '老北京刷肉4人餐',
          '套餐包括：羔羊肉，肥牛，鱼丸，酥肉，生菜，'
              '啤酒...',
          '南铜锣巷',
          '139',
          '5.7折',
          tags,
          imageUrls2,
          '190'),
      ScenicCard(
          '免费', '后海', imageUrls, '4.6分', ' | 后海/什刹海', tags2, _showDeleteDialog),
      SizedBox(
        height: 10,
      )
    ];
  }

  //构建一行功能按钮
  List<Widget> _buildTitle(
      List<String> strs, List<String> urls, List<String> tips, double width) {
    List<Widget> titleList = <Widget>[];
    for (int i = 0; i < strs.length; i++) {
      titleList.add(Flexible(
        flex: 1,
        child: MyImageButton(
            image: Image.asset(
              urls[i],
              width: width,
              height: width,
            ),
            title: strs[i],
            tip: tips[i]),
      ));
    }
    return titleList;
  }

  //构建一行功能按钮
  List<Widget> _buildTitleWithOutRed(
      List<String> strs, List<String> urls, double width) {
    List<Widget> titleList = <Widget>[];
    for (int i = 0; i < strs.length; i++) {
      titleList.add(Flexible(
        flex: 1,
        child: MyImageButton1(
            Image.asset(
              urls[i],
              width: width,
              height: width,
            ),
            strs[i]),
      ));
    }
    return titleList;
  }

  void _showDeleteDialog() {
    var dialog = SimpleDialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(15),
      ),
      titlePadding: EdgeInsets.only(top: 10),
      title: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '选择具体的理由，将减少相关的推荐',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 15, color: Colors.black54),
          ),
          SizedBox(
            height: 10,
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              _dialogButton('不感兴趣'),
              _dialogButton('去过了'),
              _dialogButton('价格不合适'),
            ],
          ),
          Container(
            decoration: BoxDecoration(
              color: CupertinoColors.lightBackgroundGray,
              borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(15),
                  bottomRight: Radius.circular(15)),
            ),
            child: Center(
              child: FlatButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text(
                  '不感兴趣',
                  style: TextStyle(fontSize: 12, color: Colors.teal),
                ),
              ),
            ),
          ),
        ],
      ),
    );
    showDialog(
      context: context,
      builder: (context) => dialog,
    );
  }

  Widget _dialogButton(String title) {
    return GestureDetector(
      onTap: () => {
        Navigator.of(context).pop(),
      },
      child: Container(
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
          child: Center(
            child: Text(
              title,
              style: TextStyle(fontSize: 15, color: Colors.black),
            ),
          ),
        ),
      ),
    );
  }
}
